import logging

import pytest

from resource.pom.hap import Hap
from resource.pom.settings import Settings
from utils.manager import MatchRules


@pytest.fixture(autouse=True)
def uninstall_hap(device):
    logging.info('预置条件：镜像版本正确、联网正常，浏览器hap安装正常')
    device.install_hap(Hap.package_path)
    connect_status = Settings.connect_wifi(device)
    assert connect_status, 'wifi连接失败'
    yield
    try:
        device.uninstall_hap(Hap.bundle_name)
    except:
        pass


class Test:
    app = Hap

    # 1.打开浏览器
    # 2.浏览器中首页选择百度
    # 3.点击百度搜索框，有结果1
    # 4.百度搜索框中输入任意字符，点击搜索，有结果2
    # 1.软键盘弹出
    # 2.软键盘收起，搜索结果中有相关搜索内容

    @pytest.mark.parametrize('setup_teardown', [app.bundle_name], indirect=True)
    def test(self, setup_teardown, device):
        logging.info('步骤1.打开浏览器')
        device.start_ability(self.app.bundle_name, self.app.ability_name)
        device.wait(5)
        logging.info('步骤2.浏览器中首页选择百度')
        device.refresh_layout()
        input_url = device.get_element_by_key('inputUrl')
        x, y = device.center_of_element(input_url)
        device.input_text(x, y, 'baidu.com')
        if device.soft_keyboard_area():
            device.close_soft_keyboard()
        device.click_element(device.get_element_by_key('actionButton0'))
        device.wait(2)
        device.click_element(device.get_element_by_key('actionButton0'))
        logging.info('步骤3.点击百度搜索框，有结果1')
        device.refresh_layout()
        device.click_element(device.get_element_by_type('searchBox'))
        logging.info('预期结果1.软键盘弹出')
        device.assert_soft_keyboard_on()
        logging.info('步骤4.百度搜索框中输入任意字符，点击搜索，有结果2')
        device.refresh_layout()
        search_box = device.get_element_by_type('searchBox')
        sx, sy = device.center_of_element(search_box)
        device.input_text(sx, sy, 'openharmony')
        device.click_element(device.get_element_by_text('百度一下'))
        logging.info('预期结果2.软键盘收起，搜索结果中有相关搜索内容')
        device.wait(8)
        device.refresh_layout()
        device.assert_text_exist('官方OpenAtom OpenHarmony')
        device.assert_text_exist('开放原子开源基金会', rule=MatchRules.Contain)
        device.assert_type_exist('link')
